package com.oweight.sagacious.auth.client.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.oweight.sagacious.api.model.user.PersonInfo;
import com.oweight.sagacious.auth.client.annotation.IgnoreUserToken;
import com.oweight.sagacious.auth.client.config.UserAuthConfig;
import com.oweight.sagacious.auth.client.jwt.UserAuthUtil;
import com.oweight.sagacious.common.context.BaseContextHandler;
import com.oweight.sagacious.common.exception.auth.UserTokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 用户鉴权拦截器
 *
 * @author SAGE
 * @version v1 2019/10/19 14:33
 */
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod;

        if (!(handler instanceof HandlerMethod)) {
            // spring boot 2.0对静态资源也进行了拦截，当拦截器拦截到请求之后，
            // 但controller里并没有对应的请求时，该请求会被当成是对静态资源的请求。
            // 此时的handler就是 ResourceHttpRequestHandler，就会抛出上述错误。
            return super.preHandle(request, response, handler);
        }
        handlerMethod = (HandlerMethod) handler;

        // 配置该注解，说明不进行用户拦截
        IgnoreUserToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
        }
        if (annotation != null) {
            return super.preHandle(request, response, handler);
        }

        String token = request.getHeader(userAuthConfig.getTokenHeader());
        if (StringUtils.isEmpty(token)) {
            // 如果request里的token为空，则在cookie里获取
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (cookie.getName().equals(userAuthConfig.getTokenHeader())) {
                        token = cookie.getValue();
                    }
                }
            }
        }

        if (StringUtils.isEmpty(token)){
            throw new UserTokenException("用户Token为空！");
        }

        if (token.contains("{")) {
            Map<String, String> parse = (Map) JSONObject.parse(token);
            token = parse.get("data");
        }

        // 获取用户信息，存全局上下文
        PersonInfo infoFromToken = userAuthUtil.getInfoFromToken2(token);
        BaseContextHandler.setToken(token);
        BaseContextHandler.setName(infoFromToken.getName());
        BaseContextHandler.setUserID(infoFromToken.getId());
        BaseContextHandler.setUsername(infoFromToken.getUsername());
        // new add
        BaseContextHandler.setPerson(infoFromToken);
        return super.preHandle(request, response, handler);
    }

    /**
     * 请求结束，清理全局数据
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
